from enum import Enum
from datetime import datetime
from exts import db


class PermissionEnum(Enum):
    BOOK = '图书',
    BOARD = '种类'
    FRONT_USER = '前台用户'
    CMS_USER = '后台用户'


class PermissionModel(db.Model):
    __tablename__='permission'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.Enum(PermissionEnum),nullable=False,unique=True)


role_permission_table = db.Table(
    "role_permission_table",
    db.Column("role_id",db.Integer,db.ForeignKey("role.id")),
    db.Column("permission_id",db.Integer,db.ForeignKey("permission.id"))
)


class RoleModel(db.Model):
    __tablename__ ='role'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(20),nullable=False,unique=True)
    desc = db.Column(db.String(200),nullable=False)
    create_time = db.Column(db.DateTime,default=datetime.now)

    permissions = db.relationship("PermissionModel",secondary=role_permission_table,backref="roles")


book_user_table=db.Table(
    "book_table_user",
    db.Column("user_id",db.Integer,db.ForeignKey("user.id")),
    db.Column("book_id",db.Integer,db.ForeignKey("book.id")),
    db.Column("is_return",db.Integer,default=False),
    db.Column("borrow_time",db.DateTime,default=datetime.now)
)


class UserModel(db.Model):
    __tablename__='user'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(20),nullable=False,unique=True)
    password = db.Column(db.String(200),nullable=False)
    email = db.Column(db.String(100),nullable=False)
    join_time = db.Column(db.DateTime,default=datetime.now)
    is_staff = db.Column(db.Boolean,default=False)
    is_active = db.Column(db.Boolean,default=True)

    # 外键
    role_id = db.Column(db.Integer,db.ForeignKey("role.id"))
    role = db.relationship("RoleModel",backref="users")
    books = db.relationship("BookModel",secondary=book_user_table,backref='users')

